package club.banyuan;

public class MaxMultithreaded extends Thread {

    private int lo, hi;
    private int[] arr;
    private double ans = 0;

    public MaxMultithreaded(int[] arr, int lo, int hi) {
        this.lo = lo;
        this.hi = hi;
        this.arr = arr;
    }

    @Override
    public void run() {
        double max = Double.MIN_VALUE;
        for (int i = lo; i < hi; i++) {
            if (Math.sin(arr[i]) > max) {
                max = Math.sin(arr[i]);
            }
        }
        ans = max;
    }

    public double getAns() {
        return ans;
    }

    /**
     * 计算数组元素的sin值之后，返回最大值。
     *
     * @param arr 目标数组
     * @return sin(数组元素)的最大值
     * @throws InterruptedException 不应该出现此异常
     */
    public static double max(int[] arr, int numThreads) throws InterruptedException {
        int len = arr.length;
        double ans = 0;

        MaxMultithreaded[] maxMultithreaded = new MaxMultithreaded[numThreads];
        for (int i = 0; i < numThreads; i++) {
            maxMultithreaded[i] = new MaxMultithreaded(arr, (i * len) / numThreads, ((i + 1) * len / numThreads));
            maxMultithreaded[i].start();
        }

        for (int i = 0; i < numThreads; i++) {
            maxMultithreaded[i].join();
            double max = Double.MIN_VALUE;
            if (maxMultithreaded[i].getAns() > max) {
                max = maxMultithreaded[i].getAns();
            }
            ans = max;
        }
        return ans;
    }
}
